#include "homepagewidget.h"
#include "ui_homepagewidget.h"
#include "util.h"
#include "videobox.h"
#include "model/datacenter.h"
#include <QScrollBar>

HomePageWidget::HomePageWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::HomePageWidget)
{
    ui->setupUi(this);

    initKindsAndTags();
    initRefreshAndTop();
    initVideos();
    connectSignalAndSlot();
}

HomePageWidget::~HomePageWidget()
{
    delete ui;
}

void HomePageWidget::initRefreshAndTop()
{
    QWidget* widget = new QWidget(this);
    widget->setFixedSize(42,94);
    widget->move(1278,618);
    widget->setStyleSheet("QPushButton{"
                          "border-radius : 21px;"
                          "border : none;"
                          "background-color : rgba(221, 221, 221, 0.4);}"
                          "QPushButton:hover{background-color : rgba(102, 102, 102, 0.4);}");

    QVBoxLayout* layout = new QVBoxLayout(widget);
    layout->setSpacing(10);
    layout->setContentsMargins(0,0,0,0);
    widget->setLayout(layout);

    QPushButton* refreshBtn = new QPushButton(widget);
    refreshBtn->setFixedSize(42,42);
    refreshBtn->setStyleSheet("border-image: url(:/images/homePage/shuaxin.png)");
    QPushButton* topBtn = new QPushButton(widget);
    topBtn->setFixedSize(42,42);
    topBtn->setStyleSheet("border-image: url(:/images/homePage/zhiding.png)");

    layout->addWidget(refreshBtn);
    layout->addWidget(topBtn);

    connect(refreshBtn, &QPushButton::clicked, this, &HomePageWidget::onRefreshBtnClicked);
    connect(topBtn, &QPushButton::clicked, this, &HomePageWidget::onTopBtnClicked);
}

void HomePageWidget::initVideos()
{
    // QGrideLayout中的视频以左上角对齐
    ui->videoGLayout->setAlignment(Qt::AlignTop | Qt::AlignLeft);
    ui->videoScroll->verticalScrollBar()->setValue(0);

    // 初始情况下，应该从服务器获取所有视频列表中的 第一页的视频，默认获取20个视频
    // 默认获取的是所有视频列表
    videoListStyle = AllStyle;
    auto dataCenter = model::DataCenter::getInstance();
    dataCenter->getAllVideoListAsync();
}

void HomePageWidget::connectSignalAndSlot()
{
    auto dataCenter = model::DataCenter::getInstance();
    // 获取所有视频列表完成信号槽绑定
    connect(dataCenter, &model::DataCenter::getAllVideoListDone, this, &HomePageWidget::updateVideoList);

    // 获取分类下视频列表完成信号槽绑定
    connect(dataCenter, &model::DataCenter::getAllVideoListInKindDone, this, &HomePageWidget::updateVideoList);

    // 获取标签下视频列表完成信号槽绑定
    connect(dataCenter, &model::DataCenter::getAllVideoListInTagDone, this, &HomePageWidget::updateVideoList);

    // 获取搜索框的文本
    connect(ui->search, &SearchLineEdit::searchVideos, this, &HomePageWidget::onSearchVideos);

    // 获取搜索视频列表完成信号槽绑定
    connect(dataCenter, &model::DataCenter::getAllVideoListInSearchDone, this, &HomePageWidget::updateVideoList);

    // 滚动条滚到底部时, 获取下一页视频
    connect(ui->videoScroll->verticalScrollBar(), &QScrollBar::valueChanged, this, &HomePageWidget::OnScrollBarValueChanged);
}

void HomePageWidget::initKindsAndTags()
{
    model::DataCenter* instance = model::DataCenter::getInstance();
    auto kindAndTags = instance->getKindAndTagClassPtr();
    QList<QString> kinds = kindAndTags->getAllKind();

    ui->classifyHLayout->setSpacing(8);
    ui->labelHLayout->setSpacing(8);

    // 创建分类
    QPushButton* kindBtn = buildSelectBtn(ui->classifys, "分类", "#3EC3FF");
    ui->classifyHLayout->addWidget(kindBtn);

    // 添加各个分类
    for(auto& kind : kinds)
    {
        QPushButton* kindBtn = buildSelectBtn(ui->classifys, kind, "#222222");
        ui->classifyHLayout->addWidget(kindBtn);
        connect(kindBtn, &QPushButton::clicked, this, [=](){
            onKindBtnClicked(kindBtn);
        });
    }
}

QPushButton *HomePageWidget::buildSelectBtn(QWidget *parent, const QString &text, const QString &color)
{
    QPushButton* btn = new QPushButton(text, parent);
    btn->setMinimumHeight(26);
    btn->setFixedWidth(text.size() * 16 + 18 + 18);
    btn->setStyleSheet("color: " + color);
    return btn;
}

void HomePageWidget::resetTags(const QList<QString> &tags)
{
    // 创建 标签
    QPushButton* tag = buildSelectBtn(ui->labels, "标签", "#3ECEFF");
    ui->labelHLayout->addWidget(tag);

    // 创建各个标签
    for(auto& tagText : tags)
    {
        QPushButton* tagBtn = buildSelectBtn(ui->labels, tagText, "#666666");
        ui->labelHLayout->addWidget(tagBtn);
        connect(tagBtn, &QPushButton::clicked, this, [=](){
            onTagBtnClicked(tagBtn);
        });
    }
}

void HomePageWidget::clearLayoutVidoes()
{
    // 清空界面QGideLayout中的所有视频
    QLayoutItem* videoItem = nullptr;
    while((videoItem = ui->videoGLayout->takeAt(0)) != nullptr) {
        delete videoItem->widget();
        delete videoItem;
    }

    // 注意还要清除DataCenter中的数据
    auto dataCenter = model::DataCenter::getInstance();
    dataCenter->getVideoListPtr()->clearVideoList();

    // 视频清空之后，将滚动条恢复到最上面
    ui->videoScroll->verticalScrollBar()->setValue(0);
}

void HomePageWidget::onKindBtnClicked(QPushButton* clickedKindBtn)
{
    if(curKind == clickedKindBtn->text()) {
        return ;
    }
    curKind = clickedKindBtn->text();
    curTag = "";

    // 当前被点击的分类设置颜色
    clickedKindBtn->setStyleSheet("background-color: #F1FDFF;"
                           "color: #3ECEFF");

    // 清除其他分类上的颜色
    QList<QPushButton*> kindBtns = ui->classifys->findChildren<QPushButton*>();
    for(auto& kindBtn : kindBtns)
    {
        if(kindBtn != clickedKindBtn && kindBtn->text() != "分类")
        {
            kindBtn->setStyleSheet("color: #222222");
        }
    }

    // 清除标签页
    QList<QPushButton*> tagBtns = ui->labels->findChildren<QPushButton*>();
    for(auto& tagBtn : tagBtns)
    {
        ui->labelHLayout->removeWidget(tagBtn);
        delete tagBtn;
    }

    auto dataCenter = model::DataCenter::getInstance();
    auto kindAndTagPtr = dataCenter->getKindAndTagClassPtr();
    resetTags(kindAndTagPtr->getTagsByKind(clickedKindBtn->text()).keys());

    // 界面上可能已经有了其他条件查询之后的视频数据
    // 再获取分类视频数据时，先将其他条件的视频清空掉
    clearLayoutVidoes();

    // 获取该分类下的视频列表并加载
    videoListStyle = KindStyle;
    dataCenter->getAllVideoListInKindAsync(kindAndTagPtr->getKindId(curKind));
}

void HomePageWidget::onTagBtnClicked(QPushButton* clickedTagBtn)
{
    if(curKind.isEmpty()) {
        return ;
    }

    if(curTag == clickedTagBtn->text()) {
        return ;
    }
    curTag = clickedTagBtn->text();

    // 当前被点击的标签设置颜色
    clickedTagBtn->setStyleSheet("background-color: #F1FDFF;"
                          "color: #3ECEFF");

    // 清除其他标签上的颜色
    QList<QPushButton*> tagBtns = ui->labels->findChildren<QPushButton*>();
    for(auto& tagBtn : tagBtns)
    {
        if(tagBtn != clickedTagBtn && tagBtn->text() != "标签")
        {
            tagBtn->setStyleSheet("color: #666666");
        }
    }

    // 清空旧的视频数据
    clearLayoutVidoes();

    videoListStyle = TagStyle;

    auto dataCenter = model::DataCenter::getInstance();
    auto kindAndTagPtr = dataCenter->getKindAndTagClassPtr();
    dataCenter->getAllVideoListInTagAsync(kindAndTagPtr->getTagId(curKind, curTag));
}

void HomePageWidget::onRefreshBtnClicked()
{
    LOG() << "刷新按钮被点击";
    // 清除旧视频
    clearLayoutVidoes();

    // 重新获取视频
    auto dataCenter = model::DataCenter::getInstance();
    auto kindAndTagPtr = dataCenter->getKindAndTagClassPtr();
    switch (videoListStyle) {
    case AllStyle:
        dataCenter->getAllVideoListAsync();
        break;
    case KindStyle:
        dataCenter->getAllVideoListInKindAsync(kindAndTagPtr->getKindId(curKind));
        break;
    case TagStyle:
        dataCenter->getAllVideoListInTagAsync(kindAndTagPtr->getTagId(curKind, curTag));
        break;
    case SearchStyle:
        dataCenter->getAllVideoListInSearchAsync(curSearch);
        break;
    default:
        LOG() << "没有该视频列表";
        break;
    }
}

void HomePageWidget::onTopBtnClicked()
{
    ui->videoScroll->verticalScrollBar()->setValue(0);
}

void HomePageWidget::onSearchVideos(const QString& searchText)
{
    if(curSearch == searchText) {
        return ;
    }
    curSearch = searchText;
    videoListStyle = SearchStyle;

    // 删除旧数据
    clearLayoutVidoes();

    // 从服务器获取搜索视频
    auto dataCenter = model::DataCenter::getInstance();
    dataCenter->getAllVideoListInSearchAsync(searchText);
}

void HomePageWidget::updateVideoList()
{
    // 获取视频列表
    auto dataCenter = model::DataCenter::getInstance();
    auto videoList = dataCenter->getVideoListPtr()->getVideoList();
    LOG()<<"已从服务器获取"<<videoList.size()<<"个视频";
    for(int i = ui->videoGLayout->count(); i < videoList.size(); ++i){
        // 构建视频显示框VideoBox
        VideoBox* videoBox = new VideoBox(videoList[i],this);
        ui->videoGLayout->addWidget(videoBox, i/4, i%4);
    }
    LOG()<<"添加到layout中的视频个数为："<<ui->videoGLayout->count();
}

void HomePageWidget::OnScrollBarValueChanged(int value)
{
    if(value != ui->videoScroll->verticalScrollBar()->maximum()) {
        return ;
    }

    auto dataCenter = model::DataCenter::getInstance();
    auto kindAndTagPtr = dataCenter->getKindAndTagClassPtr();
    switch (videoListStyle) {
    case AllStyle:
        dataCenter->getAllVideoListAsync();
        break;
    case KindStyle:
        dataCenter->getAllVideoListInKindAsync(kindAndTagPtr->getKindId(curKind));
        break;
    case TagStyle:
        dataCenter->getAllVideoListInTagAsync(kindAndTagPtr->getTagId(curKind, curTag));
        break;
    case SearchStyle:
        dataCenter->getAllVideoListInSearchAsync(curSearch);
        break;
    default:
        LOG() << "没有该视频列表";
        break;
    }
}


